############################################
#
# Used to run IR remote
#
############################################


import subprocess
import sys


# Commands
LIRC_START="/etc/init.d/lirc start"
LIRC_RESTART="/etc/init.d/lirc restart"
LIRC_STOP="fuser -k /dev/lirc0"
REMOTE_READ="mode2 -d /dev/lirc0"
FAN_ON="irsend SEND_ONCE fanremote.conf FAN_ON"
FAN_SPEED="irsend SEND_ONCE fanremote.conf FAN_SPEED"
FAN_TIMER="irsend SEND_ONCE fanremote.conf FAN_TIMER"


#####################
# Program Entrance
#####################
def main():
    # Check that there's an argument given
    if len(sys.argv) < 2:
        print("Program must take at least one argument.")
        exit(1)

    # Switch program depending on input
    arg1 = sys.argv[1].lower()
    if arg1 == 'fan':
        fan()
    elif arg1 == 'restart':
        run(LIRC_RESTART)
    elif arg1 == 'start':
        run(LIRC_START)
    elif arg1 == 'stop':
        run(LIRC_STOP)
    elif arg1 == 'read':
        remote_read()
    else:
        print("The argument was not recognized.")


#
# Run fan remote
#
def fan():
    # Fan needs additional argument
    if len(sys.argv) < 3:
        print("\n!! Fan needs another argument !!\n")
        exit(1)

    # Take fan argument
    fan_arg = sys.argv[2].lower()
    if fan_arg == 'on' or fan_arg == 'off':
        print("\nSending ON/OFF command to fan...\n")
        run(FAN_ON)
    elif fan_arg == 'speed':
        print("\nSending SPEED command to fan...\n")
        run(FAN_SPEED)
    elif fan_arg == 'up':
        print("\nIncreasing fan speed...\n")
        run(FAN_SPEED)
    elif fan_arg == 'down':
        print("\nDecreasing fan speed...\n")
        run(FAN_SPEED)
        run(FAN_SPEED)
    elif fan_arg == 'timer':
        print("\nSending TIMER command to fan...\n")
        run(FAN_TIMER)
    else:
        print("\nThe fan argument was not recognized.\n")


#
# Execute command on the command-line
#
def run(command):
    subprocess.call(command, shell=True)


#
# Read from remote
#
def remote_read():
    run(LIRC_STOP)
    output = subprocess.check_output(REMOTE_READ, shell=True)
    print "Here is output:" + output + "\nfinished"



if __name__=="__main__" : main()


    
